package com.cdhong.shop.backend.util;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description TODO
 * @Author CDHong
 * @Date Created in 2024/4/20 10:23
 * @Version 1.0
 */
public class FileUtil {

    private static final String httpURL = "http://localhost:8080/";

    /**
     * @return 返回文件保存网络地址
     * @Description 文件上传
     * @Author CDHong
     * @Param [file, type] 文件对象和保存文件夹类型
     * @Date 2024/4/20 10:24
     **/
    public static String fileUpload(MultipartFile file, String type) {
        String fileSavePath = null;
        try {
            // 获取上传文件的名字
            String fileName = file.getOriginalFilename();
            // 获取上传文件名字的后缀
            String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf("."));
            // 更改文件名为随机数.后缀名
            fileSavePath = "images/" + type + "/" + UUID.randomUUID() + suffix;
            // 当前项目所在地址
            // String projectPath = System.getProperty("user.dir");
            String projectPath = ResourceUtils.getURL("classpath:static").getPath();
            // 上传
            File saveFilePath = new File(projectPath, fileSavePath);
            file.transferTo(saveFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return fileSavePath;
        }
        return httpURL + fileSavePath;
    }
}
